import './GameMain.scss';
import React, { RefObject } from 'react';
import * as THREE from 'three';
import { Camera } from './utils/Camera';
import Role from './utils/Role';
import {CSSTransition} from "react-transition-group";
import { openAni } from '../../App/App';

interface GameMainProps {
    openAni: openAni
}

interface GameMainState {
  showStep: number
}

export default class GameMain extends React.Component<GameMainProps, GameMainState> {
    canvasRef: RefObject<HTMLCanvasElement>
    isShowFirst: boolean = true

    constructor(props: GameMainProps) {
      super(props);
      this.canvasRef = React.createRef();
      this.state = {
        showStep: 0
      };
    }

    componentDidMount() {
      const scene = new THREE.Scene();

      const renderer = new THREE.WebGLRenderer({
        canvas: (this.canvasRef.current as HTMLCanvasElement)
      });
      renderer.setSize(window.innerWidth, window.innerHeight);
      const camera = new Camera().camera;

      scene.background = new THREE.Color(0xe0e0e0);
      scene.fog = new THREE.Fog(0xe0e0e0, 20, 100);

      const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444, 1.5);
      hemiLight.position.set(0, 100, 0);
      scene.add(hemiLight);

      const dirLight = new THREE.DirectionalLight(0xffffff);
      dirLight.position.set(0, 20, 10);
      scene.add(dirLight);

      const texture = new THREE.TextureLoader().load(require('../../../assets/img/background.webp'));
      texture.wrapS = THREE.RepeatWrapping;
      texture.wrapT = THREE.RepeatWrapping;
      texture.repeat.set( 800, 300 );
      const mesh = new THREE.Mesh(new THREE.PlaneGeometry(2000, 2000), new THREE.MeshBasicMaterial({ map: texture }));
      mesh.rotation.x = -Math.PI / 2;
      scene.add(mesh);

      const grid = new THREE.GridHelper(200, 40, 0x000000, 0x000000);
      // @ts-ignore
      grid.material.opacity = 0.2;
      // @ts-ignore
      grid.material.transparent = true;
      scene.add(grid);

      console.log(new Role(scene));

      function animate() {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
      }
      animate();
    }

    goNext() {
      this.setState({
        showStep: this.state.showStep + 1
      })
    }

    initWords() {
      const random = (min: number, max: number) =>
          min + Math.floor(Math.random() * (max - min + 1));
      let crossBarGlitchTexts = document.querySelectorAll(".cross-bar-glitch");
      crossBarGlitchTexts.forEach((text, index) => {
        setTimeout(() => {
          // @ts-ignore
          text.style.opacity = 1
          let content = text.textContent;
          text.textContent = "";
          // Glitch Text
          let slice = (text as HTMLElement).dataset.slice;
          let glitchText = document.createElement("div");
          glitchText.className = "glitch";

          (glitchText as HTMLElement).style.setProperty("--slice-count", slice as string);
          for (let i = 0; i <= Number(slice); i++) {
            let span = document.createElement("span");
            span.textContent = content;
            span.style.setProperty("--i", `${i + 1}`);
            if (i !== Number(slice)) {
              span.style.animationDelay = `${800 + random(100, 300)}ms`;
            }
            glitchText.append(span);
          }
          text.appendChild(glitchText);
          // Cross Bars
          let bars = document.createElement("div");
          bars.className = "bars";
          for (let i = 0; i < 5; i++) {
            let bar = document.createElement("div");
            bar.className = "bar";
            bars.append(bar);
          }
          text.append(bars);
        }, index * 300)
      });
    }

    render() {
      if(this.props.openAni.gameShow && this.isShowFirst) {
          Promise.resolve().then(this.initWords)
          this.isShowFirst = false
      }
      return <div>
        <canvas id='game_canvas' ref={this.canvasRef} className={'f-center'}/>
        <CSSTransition in={this.state.showStep < 2} unmountOnExit timeout={1000} classNames='my-node'>
            <div className={'f-center game-main-cover'}>
                <CSSTransition in={this.state.showStep === 0} unmountOnExit timeout={1000} classNames='my-node'>
                   <div className={'f-center game-main-title'}>
                       <h1 className="cross-bar-glitch" data-slice="20">
                           A ThreeJs Game
                       </h1>
                       <h1 className="cross-bar-glitch" data-slice="20">
                           Not Modal, Not Designer, Not Money
                       </h1>
                       <h1 className="cross-bar-glitch" data-slice="20">
                           Not finished
                       </h1>
                       <h1 className="cross-bar-glitch cross-bar-button" data-slice="20" onClick={() => this.goNext()}>
                           Click Me
                       </h1>
                   </div>
                </CSSTransition>
                <CSSTransition in={this.state.showStep === 1} unmountOnExit timeout={1000} classNames='my-node'>
                    <div className="shadow">
                        <div className="card">
                            <div className="card-header">Hover Me</div>
                            <div className="card-body">
                                <dl>
                                <span>
                                    <dt>状态：</dt>
                                    <dd>未完成，只能移动</dd>
                                </span>
                                    <span>
                                    <dt>操作：</dt>
                                    <dd>wasd控制方向，左键拖动视角</dd>
                                </span>
                                    <span>
                                    <dt>退出：</dt>
                                    <dd>esc、enter、空格即可退出进入介绍</dd>
                                </span>
                                    <span>
                                    <dd>
                                        <div className={'last-button'}>
                                            <button className="btn-share" onClick={() => this.goNext()}>
                                              <span className="btn-overlay">开始游戏</span>
                                              <section>冲</section>
                                              <section>冲</section>
                                              <section>冲</section>
                                              <section>!</section>
                                            </button>
                                        </div>
                                    </dd>
                                </span>
                                </dl>
                            </div>
                        </div>
                    </div>
                </CSSTransition>
            </div>
        </CSSTransition>
      </div>;
    }
}
